#! /usr/bin/python
# -*- coding: utf-8 -*-
# 角色权限相关

from django.urls import reverse
from django.db import connection, connections
from django.utils.html import conditional_escape 
from django.http import HttpResponse
from django.shortcuts import redirect, render_to_response, HttpResponseRedirect, render
from django.views.generic import ListView, View
#==========================================

from public_util.util.AutoUrl import Route
from .menu import MenuTree
from ...models.admin import Role, Resource
from ...models.pack import Handle, Project
from public_util.util import trace_msg


@Route()
def role_list(request):
    """角色列表"""
    if not request.admin.is_root and u'管理普通角色' in request.allow_menu.keys():
        not_is_root = False
        request.admin.is_root = True
        list_record = request.admin.get_not_admin_resource('role')
        request.admin.is_root = False
    if request.admin.is_manager:
        list_record = request.admin.get_resource('role')
    return render_to_response('system/role_list.html', locals())


@Route()
def role_edit(request, id=0):
    """角色编辑"""
    id = int(request.REQUEST.get('id', '0'))
    is_copy = request.REQUEST.get('copy', '')
    resource = {}

    if id:
        if request.admin.is_root:
            role = request.admin.get_resource('role').get(id=id)
            if is_copy:
                role.name = '%s-copy' % role.name
        else:
            request.admin.is_root = True
            role = request.admin.get_not_admin_resource('role').get(id=id)
            if is_copy:
                role.name = '%s-copy' % role.name
            request.admin.is_root = False
    else:
        role = Role()
        role.id = id
    roles = request.admin.get_resource('role').exclude(id=role.id)

    # 将角色拥有的资源查询缓存
    resource_ids = role.resource_ids
    project_objs = Project.objects.all()
    # resource_ids_key = 'role%s_resource'%role.id
    # resource_ids = cache.get(resource_ids_key)
    # if not resource_ids:
    #     resource_ids = role.resource_ids
    #     # cache.set(resource_ids_key,resource_ids,60)
    #     # update_cache = True

    if id and not request.admin.is_root:
        menus = MenuTree(Role.objects.get(id=id).get_resource('menu')).get_list_record()

    else:
        menus = MenuTree(request.admin.get_resource('menu').all().order_by('parent_id')).get_list_record()
    select_pro_ids = list(role.resource_ids.get("project", {}))
    # agent_channels_dict = get_group_channels_dict()
    # group_servers_dict = groups_servers(request)
    # platforms = request.admin.get_resource('platform')
    # server_cache = group_server_cache(request, locals(),type='query_or_role' )#获取服务器页面缓存
    # select_group_ids = list(resource_ids.get('server_group', {}))
    # select_server_ids = list(resource_ids.get('server', {}))

    res = render_to_response('system/role_edit.html', locals())
    return res


@Route()
def role_save(request, id=0):
    """角色保存"""
    try:
        id = int(request.REQUEST.get('id', '0'))
        if id > 0:
            Handle.create_handle(user_id=request.admin.id, ope_id=12,
                                 user=request.admin.alias)
            if request.admin.is_root:
                role = request.admin.get_resource('role').get(id=id)
            else:
                request.admin.is_root = True
                role = request.admin.get_not_admin_resource('role').get(id=id)
                request.admin.is_root =False
        else:
            role = Role()
        role.set_attr('name', request.REQUEST.get('name', ''), null=False)
        role.set_attr('remark', request.REQUEST.get('remark', ''), null=True)
        role.set_attr('type', request.REQUEST.get('type', Role.RoleType.NORMAL), null=False)
        role.create_resource('menu', request.REQUEST.getlist('menu_id'))
        role.create_resource('project', request.REQUEST.getlist('pro_id'))
        # role.create_resource('channel',request.REQUEST.getlist('channel_id'))
        # role.create_resource('agent',request.REQUEST.getlist('agent_id'))
        # role.create_resource('server',request.REQUEST.getlist('server_id'))
        # role.create_resource('server_group',request.REQUEST.getlist('server_group_id'))
        # role.create_resource('platform',request.REQUEST.getlist('platform_id'))
        # role.remark = request.REQUEST.getlist('agent_id')  # 新增分区ID，为了通过分区查询渠道权限
        manager_role_ids = []  # 只有管理员才能管理其他角色
        if int(role.type) == Role.RoleType.ADMIN:
            manager_role_ids = request.REQUEST.getlist('manager_role_id')
        role.create_resource('role', manager_role_ids)
        role.save()
        for r in request.admin.get_roles().filter(type=Role.RoleType.ADMIN):
            r.add_resource_member('role', role.id)
    except Exception as e:
        err_msg = trace_msg()
    return render_to_response('feedback.html', locals())


@Route()
def role_remove(request, id=0):
    """删除角色"""
    try:
        role_ids = request.REQUEST.getlist('id')
        if role_ids:
            for r in request.admin.get_resource('role').filter(id__in=role_ids):
                r.delete(using='write')
    except Exception as e:
        err_msg = trace_msg()
    return render_to_response('feedback.html', locals())
